package com.kaoyaya.delivery.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EFragment;
import com.googlecode.androidannotations.annotations.ViewById;
import com.kaoyaya.delivery.activity.R;
import com.kaoyaya.delivery.activity.SlidingActivity;
import com.kaoyaya.delivery.adapter.OrderAdapter;
import com.kaoyaya.delivery.data.Constants;
import com.kaoyaya.delivery.data.DataHelper;
import com.kaoyaya.delivery.data.entity.Client;
import com.kaoyaya.delivery.data.entity.OrderItem;
import com.kaoyaya.delivery.data.entity.Result;
import com.kaoyaya.util.CommUtil;
import com.kaoyaya.view.ClientInfoDialog;

@EFragment(R.layout.fmt_cart)
public class CartFmt extends Fragment {

	@ViewById TextView tvTitle, tvTotal, tvCost, tvBalance;
	@ViewById ListView lvOrder;
	@ViewById Button btnDelivery;
	OrderAdapter orderAdapter;
	@Bean DataHelper dataHelper;
	final int IS_GOLD = 0, IS_DELIVERYORDER = 1;
	double balance, cost;
	LayoutInflater inflater;
	Dialog pgDialog;
	
	private SlidingActivity activity;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		this.inflater = inflater;
		return null;
	}
	
	@AfterViews
	void initView() {
		this.activity = (SlidingActivity) getActivity();
		tvTitle.setText("发货管理");
		calculate();
		orderAdapter = new OrderAdapter(getActivity(), clickListener, Constants.cart);
		lvOrder.setAdapter(orderAdapter);
		dataHelper.setCallbackHandler(callbackHandler);
		dataHelper.getUserAccount(IS_GOLD);
	}

	/**
	 * 计算 
	 * @author Goven
	 * @date 2013-6-2
	 */
	void calculate() {
		double total = 0;
		activity.updateCart();
		for (OrderItem orderItem : Constants.cart) {
			total += orderItem.getPrice();
		}
		cost = total / 10;
		tvTotal.setText(String.valueOf(total));
		tvCost.setText(String.valueOf(cost));
	}
	
	@Click
	void btnDelivery() {
		if (cost <= balance) {
			if (Constants.cart.size() == 0) {
				AlertDialog.Builder builder = new Builder(getActivity()).setMessage("请先添加商品！");
				builder.setTitle("提示");
				builder.setPositiveButton("确认", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).create().show();
			} else {
				Dialog dialog = new ClientInfoDialog(getActivity(), R.style.dialog, this);
				dialog.show();
			}
		} else {
			AlertDialog.Builder builder = new Builder(getActivity()).setMessage("余额不足，请充值！");
			builder.setTitle("提示");
			builder.setPositiveButton("确认", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).create().show();
		}
	}
	
	public void ensureDelivery(Client client) {
		if (Constants.authGlobal || Constants.authDelivery) {
			pgDialog = CommUtil.createLoadingDialog(activity, "正在发货,请稍等...");
			List<OrderItem> orderItems = new ArrayList<OrderItem>();
			for (OrderItem orderItem : Constants.cart) {
				OrderItem temp = new OrderItem();
				temp.setType(orderItem.getType());
				temp.setNo(orderItem.getNo());
				orderItems.add(temp);
			}
			dataHelper.deliveryOrder(IS_DELIVERYORDER, 1, client, orderItems);
		}
	}
	
	View.OnClickListener clickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.ivDelete:
				Integer position = (Integer) v.getTag();
				Constants.cart.remove(position);
				orderAdapter.deleteOrderItem(position);
				orderAdapter.notifyDataSetChanged();
				calculate();
				break;
			default:
				break;
			}
		}
	};
	
	Handler callbackHandler = new Handler() {
		public void handleMessage(Message msg) {
			Object result = msg.obj;
			switch (msg.what) {
			case IS_GOLD:
				balance = (Double) result;
				tvBalance.setText(String.valueOf(balance));
				break;
			case IS_DELIVERYORDER:
				Result $result = (Result) result;
				if ($result != null && $result.getResultCode() == 1) {
					Toast.makeText(getActivity(), "恭喜你，发货成功！", Toast.LENGTH_SHORT).show();
					Constants.cart.clear();
					activity.updateCart();
					Constants.gold = balance - cost;
					activity.updateBalance();
				} else {
					Toast.makeText(getActivity(), "抱歉，发货失败！", Toast.LENGTH_SHORT).show();
				}
				break;
			}
			if (pgDialog != null) {
				pgDialog.cancel();
			}
		}
	};
	
}
